<template>
  <div class="project-setting project-addition-setting">
    <div class="setting-header">
      <div class="setting-title-detail">
        {{ $t('common.projectManage.additionTip') }}
      </div>
      <div class="setting-action">
        <el-button type="primary" @click="onConnectorCreateHandler"><i class="iconfont icon-add2"></i>{{ $t('common.base.add2') }}</el-button>
      </div>
    </div>
    <div class="setting-content" v-loading="loading">
      <!-- 已添加附加组件 -->
      <template v-if="cardList.length">
        <div class="task-type-list">
          <card-item
            class="task-type-item"
            v-for="(item, idx) in cardList"
            :key="item.id"
            :card.sync="cardList[idx]"
            @deleteCard="onDeleteCard"
            @editName="editCardName"
            @edit="onEditConnectorCardHandler"
          ></card-item>
        </div>
      </template>
      <template v-else>
        <no-data-view :notice-msg="$t('common.base.noData')"></no-data-view>
      </template>
      <!-- end 已添加附加组件 -->
    </div>

      <!-- start 新建连接器弹窗 -->
      <ConnectorModuleCreateConnectorDialog
        :title="connectorCreateModalTitle"
        :visible="isShowCreateConnectorModal"
        :bizTypeId="templateId"
        :toBizType="toBizType"
        :fromBizType="fromBizType"
        :fromBizTypeName="templateName"
        @close="onCloseCreateConnectorModal"
        @finish="initCard"
      />
      <!-- end 新建连接器弹窗 -->

       <!-- start 编辑连接器弹窗 -->
       <ConnectorModuleEditConnectorDialog
        :title="connectorEditModalTitle" 
        :fromBizTypeName="templateName"
        :visible="isShowEditConnectorModal"
        :connectorInfo="connectorInfo"
        @close="onCloseEditConnectorModal"
        @finish="initCard"
      />
      <!-- end 编辑连接器弹窗 -->
      
      <!-- 编辑连接器名称 -->
      <ConnectorListViewCreateDialog
        :title="$t('common.connector.editConnector')"
        :value="formValue"
        :visible="isShowEditConnectorNameModal"
        :fields="CreateConnectorModalFields"
        :is-connector="true"
        @close="onDialogCloseHandler"
        @confirm="onDialogConfirmHandler"
        @input="onDialogUpdateHandler"
    >
    </ConnectorListViewCreateDialog>
      <!-- end 编辑连接器弹窗 -->

  </div>
</template>
<script>
import { ConnectorModuleCardSettingProjectMixin, ConnectorModuleCardSettingMixin } from '@src/modules/connector'
import * as ProjectManage from '@src/api/ProjectManage.ts';
import CardItem from '@src/modules/setting/projectManage/components/AdditionalSetting/components/CardItem.vue';
import NoDataView from '@src/component/common/NoDataViewNew';
import { getConnectorName, updateConnectorName } from '@src/modules/connector/api';
import { message } from '@src/util/message'
import { ConnectorListViewCreateDialog } from '@src/modules/connector/view/list/components';
import i18n, { t } from '@src/locales'
import { cloneDeep } from 'lodash'

const CreateConnectorModalFields = [
  {
    fieldName: 'name',
    formType: 'text',
    displayName: t('common.base.name'),
    placeHolder: t('common.placeholder.inputName'),
    isNull: 0,
    maxlength: 20
  },
  {
    fieldName: 'description',
    formType: 'textarea',
    displayName: t('common.base.explain'),
    placeHolder: t('common.connector.fields.description.placeholder1'),
    isNull: 1,
    maxlength: 500
  }
]
export default {
  name: 'additional-setting',
  mixins: [ConnectorModuleCardSettingProjectMixin, ConnectorModuleCardSettingMixin],
  data() {
    return  {
      loading: false,
      cardList: [],
      formValue: {},
      isShowEditConnectorNameModal: false,
      CreateConnectorModalFields,
    }
  },
  components: {
    NoDataView,
    CardItem,
    ConnectorListViewCreateDialog
  },
  props: {
    templateId: {
      type: String | Number,
      default: '',
    },
    templateName: {
      type: String | Number,
      default: '',
    }
  },

  computed: {
 
  },
  // 页面初始化
  mounted() {
    this.initCard()
  },
  methods: {
    async editCardName(card) {
      try {
        const res = await getConnectorName(card?.config?.connectorInfo)
        if(res.status == 0){ 
          const { data = {} } = res
          this.isShowEditConnectorNameModal = true
          this.formValue = cloneDeep({
            id: data.id,
            name:data.connectorName,
            description:data.connectorRemarks || '',
            titleLanguage: {...(data.titleLanguage || {}), [i18n.locale]:data.connectorName},
            descLanguage: data.descLanguage || {}
          })
        } else {
          message.error(res.message)
        }
      } catch(error) {
        console.log(error)
      }
    },

    onDialogCloseHandler(){
      this.isShowEditConnectorNameModal = false
      this.resetFormValue()
    },
    resetFormValue(){
      this.formValue = {
        id: '',
        name:'',
        description:''
      }
    },

    onDialogUpdateHandler(info) {
      let { fieldName, newValue } = info
      if( !fieldName )return;
      this.formValue[fieldName] = newValue
    },

    onDialogConfirmHandler(){
      const params = {
        id: this.formValue.id,
        connectorName: this.formValue.name,
        connectorRemarks: this.formValue.description,
        titleLanguage:this.formValue?.titleLanguage || {},
        descLanguage:this.formValue?.descLanguage || {}
      }
      updateConnectorName(params).then(res=>{
        if(res.status == 0){
          // 更新附加组件列表
          this.$emit('finish')
          message.success(this.$t('common.base.tip.modifySuccess'))
          this.onDialogCloseHandler()
          this.initCard()
        }else{
          message.error(res.message)
        }
      })
    },
    /**
     * 删除对应的Card
     */
     async onDeleteCard(card) {
      try {
        const rs = await ProjectManage.deleteCard({ id: card.id });
        if(rs.success) {
          this.$message.success(this.$t('common.base.deleteSuccess'));
          this.initCard()
        } else {
          this.$message.error(rs.message);
        }
      } catch (e) {
        console.log('[fetch deleteConnectorDataFromPaasItem error]', e);
      }
    },
    // 获取列表
    async initCard(){
      try{
        let {data,status,message} = await ProjectManage.getAllCardList({projectTypeId: this.templateId});
        this.loading = false;
        if(status === 0){
          this.cardList = data;

          this.cardList = this.cardList.map((item) => {
            return {
              ...item,
              config: item.bizConfig,
            }
          })
        }else{
          this.$message.error(message);
        }
      }catch(err){
        console.error(err);
        this.loading = false;
      }
    },
  }
}
</script>
<style lang="scss" scoped>
.project-setting {
  height: 100%;
  background: rgb(236, 240, 245);
  overflow: hidden;
  .setting-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #fff;
    padding: 16px;
    border-radius: 4px;
    margin-bottom: 12px;
    .setting-title-detail {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #595959;
      line-height: 20px;
    }
    .setting-title {
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #262626;
      line-height: 22px
    }
  }
  .setting-content {
    width: calc(100% + 12px);
    height: calc(100% - 76px);
    overflow-y: auto;

    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    .app-nodata-view {
      width: 100%;
      height: 100%;
      background: #fff;
      border-radius: $button-radius-base;
    }
    .task-type-list {
      @include dynamic-card-list(2, 'task-type-item');
      .task-type-item {
        margin: 0 12px 12px 0;
      }
    }
  }
}
.project-addition-setting {
  background: #ecf0f5;
}
</style>